package com.ysj.aipicturebe.manager.websocket.disruptor;

import cn.hutool.json.JSONUtil;
import com.lmax.disruptor.WorkHandler;

import com.ysj.aipicturebe.manager.websocket.PictureEditHandler;
import com.ysj.aipicturebe.manager.websocket.model.PictureEditMessageTypeEnum;
import com.ysj.aipicturebe.manager.websocket.model.PictureEditRequestMessage;
import com.ysj.aipicturebe.manager.websocket.model.PictureEditResponseMessage;
import com.ysj.aipicturebe.model.entity.User;
import com.ysj.aipicturebe.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;

import javax.annotation.Resource;

/**
 * 图片编辑事件处理器（消费者）
 */
@Component // 标注为 Spring 的组件，便于 Spring 容器管理
@Slf4j // 引入日志功能，方便记录日志
public class PictureEditEventWorkHandler implements WorkHandler<PictureEditEvent> {

    @Resource // 注入图片编辑处理器
    private PictureEditHandler pictureEditHandler;

    @Resource // 注入用户服务
    private UserService userService;

    @Override
    public void onEvent(PictureEditEvent pictureEditEvent) throws Exception {
        // 获取图片编辑请求消息
        PictureEditRequestMessage pictureEditRequestMessage = pictureEditEvent.getPictureEditRequestMessage();
        // 获取 WebSocket 会话
        WebSocketSession session = pictureEditEvent.getSession();
        // 获取当前用户
        User user = pictureEditEvent.getUser();
        // 获取图片 ID
        Long pictureId = pictureEditEvent.getPictureId();
        // 获取到消息类别
        String type = pictureEditRequestMessage.getType();
        // 根据消息类型枚举值获取对应的枚举
        PictureEditMessageTypeEnum pictureEditMessageTypeEnum = PictureEditMessageTypeEnum.getEnumByValue(type);
        // 根据消息类型处理消息
        switch (pictureEditMessageTypeEnum) {
            case ENTER_EDIT: // 处理进入编辑的消息
                pictureEditHandler.handleEnterEditMessage(pictureEditRequestMessage, session, user, pictureId);
                break;
            case EXIT_EDIT: // 处理退出编辑的消息
                pictureEditHandler.handleExitEditMessage(pictureEditRequestMessage, session, user, pictureId);
                break;
            case EDIT_ACTION: // 处理编辑操作的消息
                pictureEditHandler.handleEditActionMessage(pictureEditRequestMessage, session, user, pictureId);
                break;
            default: // 处理其他未知消息类型
                // 构造错误响应消息
                PictureEditResponseMessage pictureEditResponseMessage = new PictureEditResponseMessage();
                pictureEditResponseMessage.setType(PictureEditMessageTypeEnum.ERROR.getValue()); // 设置消息类型为错误
                pictureEditResponseMessage.setMessage("消息类型错误"); // 设置错误提示信息
                pictureEditResponseMessage.setUser(userService.getUserVO(user)); // 设置用户信息
                // 发送错误消息到客户端
                session.sendMessage(new TextMessage(JSONUtil.toJsonStr(pictureEditResponseMessage)));
                break;
        }
    }
}